package bizapi.sinosoft.com.provider.order.adapter.impl;

import bizapi.sinosoft.com.provider.CommonResponse;
import bizapi.sinosoft.com.provider.order.adapter.OrderAdapter;
import bizapi.sinosoft.com.provider.order.vo.request.JdOrderConstant;
import bizapi.sinosoft.com.provider.order.vo.response.SelectCSkuVO;
import bizapi.sinosoft.com.provider.order.vo.response.SelectOrderVO;
import bizapi.sinosoft.com.provider.order.vo.response.SelectPSkuVO;
import bizapi.sinosoft.com.provider.order.vo.response.SelectSubOrderVO;
import cart.api.OrderMainApi;
import cart.model.order.OrderItem;
import cart.model.order.OrderMain;
import cart.model.order.SubOrder;
import cart.model.order.SubOrderItem;
import cart.model.repository.order.OrderRepos;
import cart.model.repository.order.SubOrderRepos;
import cms.api.OrganizationApi;
import cms.model.OrgAccountCtrlHistory;
import com.alibaba.fastjson.JSON;
import com.weibo.api.motan.config.springsupport.annotation.MotanReferer;
import goods.model.Goods;
import goods.model.Product;
import goods.model.ProductFashion;
import goods.model.repository.GoodsFashionRepos;
import goods.model.repository.GoodsRepos;
import goods.model.repository.ProductFashionRepos;
import jd.api.request.order.OrderEntity;
import jd.api.request.product.SkuEntity;
import jd.api.request.product.SkuIdAndNumEntity;
import jd.api.response.order.OrderUniteSubmitResp;
import jd.api.service.order.JdOrderApi;
import jd.api.service.product.JdProductApi;
import jd.api.vo.product.PriceVO;
import jd.model.address.NationalAddress;
import jd.model.repository.NationalAddressRepos;
import jd.restful.model.SubmitOrderVO;
import jd.restful.repository.SubmitOrderDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import utils.GlobalContants;
import utils.Lang;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by xujingfeng on 2016/12/15.
 */
@Service
public class JdOrderAdapter implements OrderAdapter {

    final Logger logger = LoggerFactory.getLogger(JdOrderAdapter.class);

    @Autowired
    SubmitOrderDao submitOrderDao;

    @Value("${cyOrganizationId:3561a343-7b1f-45ee-a2b8-7e0e09ee8d00}")
    String cyOrganizationId;

    @Value("${cyMemberId:b62ff6b5-91b6-46ff-bea4-ab0071782c9d}")
    String cyMemberId;

    @Value("${cyName:畅悦科技}")
    String cyName;

    @Override
    @Transactional
    public CommonResponse<String> takeOrder(SubmitOrderVO submitOrderVO) {
        CommonResponse<String> commonResponse = new CommonResponse<>();
        commonResponse.setSuccess(false);
        //保存表单提交记录
        try {
            if (Lang.isEmpty(submitOrderVO.getThirdOrder())) {
                commonResponse.setResultMessage("第三方订单编号不能为空");
                return commonResponse;
            } else {
                submitOrderDao.saveAndFlush(submitOrderVO);
                TransactionAspectSupport.currentTransactionStatus().flush();
            }
        } catch (DataIntegrityViolationException cve) {
            //防止订单号重复
            commonResponse.setResultMessage("第三方订单编号[" + submitOrderVO.getThirdOrder() + "]已经存在,请不要重复提交订单");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return commonResponse;
        } catch (Exception e) {
            commonResponse.setResultMessage(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return commonResponse;
        }
        try {
            //获取下单的商品列表
            List<SkuIdAndNumEntity> sku;
            try {
                sku = JSON.parseArray(submitOrderVO.getSku(), SkuIdAndNumEntity.class);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                commonResponse.setResultMessage("商品列表sku参数有误");
                return commonResponse;
            }
            boolean flag;
            OrderMain orderMain = new OrderMain();
            flag = genOrder(orderMain, submitOrderVO, commonResponse);
            //生成orderMain失败，立刻返回
            if (!flag) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return commonResponse;
            }
            //生成orderItems失败，立刻返回
            flag = genOrderItem(orderMain, submitOrderVO, commonResponse);
            if (!flag) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return commonResponse;
            }
            //保存orderMain之后，orderNo已经生成
            orderRepos.save(orderMain);
            //回写畅悦申请的表单信息
            submitOrderVO.setTaipingOrderNo(orderMain.getOrderNo());
            submitOrderDao.saveAndFlush(submitOrderVO);
             /*校验畅悦在太平的余额*/
            BigDecimal totalFare = BigDecimal.ZERO;
            //获取总价
            for (SkuIdAndNumEntity skuIdAndNumEntity : sku) {
                List<PriceVO> price = jdProductApi.getPrice(new SkuEntity(skuIdAndNumEntity.getId().toString()));
                totalFare = totalFare.add(price.get(0).getPrice().multiply(new BigDecimal(skuIdAndNumEntity.getNum())));
            }
            Map returnMap = organizationApi.organizationAccountCtrl(cyOrganizationId, totalFare, OrgAccountCtrlHistory.OPERATION_TYPE_DEFOREHAND, cyName, cyMemberId, submitOrderVO.getTaipingOrderNo());
            //预占余额
            if (!returnMap.get(GlobalContants.ResponseString.STATUS).equals(GlobalContants.ResponseStatus.SUCCESS)) {
                commonResponse.setResultMessage(returnMap.get(GlobalContants.ResponseString.MESSAGE).toString());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return commonResponse;
            }
            //封装京东下单实体
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setThirdOrder(orderMain.getOrderNo());//第三方订单号
            orderEntity.setSku(sku);//商品列表
            orderEntity.setName(submitOrderVO.getName());//下单人姓名
            orderEntity.setProvince(submitOrderVO.getProvince());//省
            orderEntity.setCity(submitOrderVO.getCity());//市
            orderEntity.setCounty(submitOrderVO.getCounty());//乡
            orderEntity.setTown(submitOrderVO.getTown());//镇
            orderEntity.setAddress(submitOrderVO.getAddress());//详细地址
            orderEntity.setMobile(submitOrderVO.getMobile());//手机号码
            if(Lang.isEmpty(submitOrderVO.getEmail())){
                orderEntity.setEmail(JdOrderConstant.email);//太平邮箱
            }else{
                orderEntity.setEmail(submitOrderVO.getEmail());//客户邮箱
            }
            orderEntity.setInvoiceState(JdOrderConstant.invoiceState);
            orderEntity.setInvoiceType(JdOrderConstant.invoiceType);
            orderEntity.setSelectedInvoiceTitle(JdOrderConstant.selectedInvoiceTitle);
            orderEntity.setInvoiceName(JdOrderConstant.invoiceName);
            orderEntity.setInvoiceContent(JdOrderConstant.invoiceContent);
            orderEntity.setPaymentType(JdOrderConstant.paymentType);
            orderEntity.setIsUseBalance(JdOrderConstant.isUseBalance);
            orderEntity.setSubmitState(JdOrderConstant.submitState);
            orderEntity.setDoOrderPriceMode(submitOrderVO.getDoOrderPriceMode());
            orderEntity.setOrderPriceSnap(submitOrderVO.getOrderPriceSnap());
            //去京东下单
            final OrderUniteSubmitResp orderUniteSubmitResp = jdOrderApi.placeOrder(orderEntity);
            commonResponse.setResultMessage(orderUniteSubmitResp.getResultMessage());
            commonResponse.setCode(orderUniteSubmitResp.getCode());
            commonResponse.setResultMessage(orderUniteSubmitResp.getResultMessage());
            if (!orderUniteSubmitResp.getSuccess()) {
                //下单失败
                //返回余额
                organizationApi.organizationAccountCtrl(cyOrganizationId, totalFare, OrgAccountCtrlHistory.OPERATION_TYPE_CANCEL, cyName, cyMemberId, submitOrderVO.getTaipingOrderNo());
                //获取所有商品的京东商品编号
                final List<String> skuIds = new ArrayList<>();
                List<SkuIdAndNumEntity> skuIdAndNumEntitys = orderEntity.getSku();
                for (SkuIdAndNumEntity skuIdAndNumEntity : skuIdAndNumEntitys) {
                    skuIds.add(skuIdAndNumEntity.getId().toString());
                }
                //价格快照校验失败
                if ("3019".equals(orderUniteSubmitResp.getResultCode())) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            changePrice(skuIds);
                            logger.info("changePrice");
                        }
                    }, "changePrice").start();
                }
                //取消订单
                orderMain.setStatus(OrderMain.order_status_cancel);
                orderRepos.save(orderMain);
                submitOrderDao.delete(submitOrderVO);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            } else {
                //下单成功
                //确认扣款
                organizationApi.organizationAccountCtrl(cyOrganizationId, totalFare, OrgAccountCtrlHistory.OPERATION_TYPE_SURE, cyName, cyMemberId, submitOrderVO.getTaipingOrderNo());
                //建立orderMain和jdOrderId的关联
                orderMain.setThirdOrderNo(orderUniteSubmitResp.getResult().getJdOrderId().toString());
                //2.2.2修改订单状态为未发货
                orderMain.setStatus(OrderMain.order_status_ounfilled);
                orderMain.setSumPrice(orderUniteSubmitResp.getResult().getOrderPrice());
                orderMain.setFreight(orderUniteSubmitResp.getResult().getFreight());
                //保存
                orderRepos.save(orderMain);
                TransactionAspectSupport.currentTransactionStatus().flush();
                //京东拆单
                try{
                    jdOrderHelper.splitOrder(orderMain.getId(), false);
                }catch (Exception e){
                    logger.error(e.getMessage(),e);
                }
                //返回订单号
                commonResponse.setSuccess(true);
                commonResponse.setResult(orderMain.getOrderNo());
            }
        } catch (Exception e) {
            commonResponse.setResult(null);
            commonResponse.setResultCode(null);
            commonResponse.setCode(null);
            commonResponse.setSuccess(false);
            commonResponse.setResultMessage(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage(), e);
        }
        return commonResponse;
    }

    @Override
    public CommonResponse<SelectOrderVO> selectOrder(String orderNo) {
        CommonResponse<SelectOrderVO> commonResponse = new CommonResponse<>();
        try {
            OrderMain orderMain = orderRepos.findByOrderNo(orderNo);
            if (Lang.isEmpty(orderMain)) {
                commonResponse.setSuccess(false);
                commonResponse.setResultMessage("订单号[" + orderNo + "]不存在");
                return commonResponse;
            }
            //封装返回实体
            SelectOrderVO selectOrderVO = copySelectOrderVO(orderMain);
            commonResponse.setResult(selectOrderVO);
            commonResponse.setSuccess(true);
        } catch (Exception e) {
            commonResponse.setSuccess(false);
            commonResponse.setResultMessage(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return commonResponse;
    }

    private SelectOrderVO copySelectOrderVO(OrderMain orderMain) {
        SelectOrderVO selectOrderVO = new SelectOrderVO();
        selectOrderVO.setFreight(orderMain.getFreight());
        selectOrderVO.setStatus(orderMain.getStatus());
        selectOrderVO.setSumPrice(orderMain.getSumPrice());
        selectOrderVO.setCreateTime(orderMain.getCreateTime());
        selectOrderVO.setPorderId(orderMain.getOrderNo());
        //封装子订单
        selectOrderVO.setSubOrders(new ArrayList<SelectSubOrderVO>());
        for (SubOrder subOrder : orderMain.getSubOrders()) {
            SelectSubOrderVO selectSubOrderVO = new SelectSubOrderVO();
            selectOrderVO.getSubOrders().add(selectSubOrderVO);
            selectSubOrderVO.setCorderId(subOrder.getSubOrderNo());
            selectSubOrderVO.setCskus(new ArrayList<SelectCSkuVO>());
            for (SubOrderItem subOrderItem : subOrder.getSubOrderItems()) {
                SelectCSkuVO selectCSkuVO = new SelectCSkuVO();
                selectSubOrderVO.getCskus().add(selectCSkuVO);
                selectCSkuVO.setCount(subOrderItem.getCount());
                selectCSkuVO.setProductName(subOrderItem.getOrderItem().getProductName());
                selectCSkuVO.setSalePrice(subOrderItem.getOrderItem().getSalePrice());
                Goods goods = goodsRepos.findById(subOrderItem.getOrderItem().getGoodsId());
                selectCSkuVO.setSkuId(goods.getSku());
            }
        }
        //封装主商品列表
        selectOrderVO.setPskus(new ArrayList<SelectPSkuVO>());
        for (OrderItem orderItem : orderMain.getOrderItems()) {
            SelectPSkuVO selectPSkuVO = new SelectPSkuVO();
            selectOrderVO.getPskus().add(selectPSkuVO);
            Goods goods = goodsRepos.findById(orderItem.getGoodsId());
            selectPSkuVO.setSkuId(goods.getSku());
            selectPSkuVO.setSalePrice(orderItem.getSalePrice());
            selectPSkuVO.setProductName(orderItem.getProductName());
            selectPSkuVO.setCount(orderItem.getCount());
        }
        return selectOrderVO;
    }

    /**
     * 提供给匿名内部类线程去修改价格
     *
     * @param skuIds
     */
    private void changePrice(List<String> skuIds) {
        for (String skuId : skuIds) {
            List<PriceVO> price = jdProductApi.getPrice(new SkuEntity(skuId));
            if (!Lang.isEmpty(price)) {
                PriceVO priceVO = price.get(0);
                logger.info("==price=={}", priceVO.getPrice());
                goodsRepos.updatePriceBySku(skuId, priceVO.getPrice(), priceVO.getJdPrice());
                goodsRepos.updateTime(skuId, new Date());
                productFashionRepos.updatePriceBySku(skuId, priceVO.getPrice(), priceVO.getJdPrice());
                productFashionRepos.updateTime(skuId, new Date());
            }
        }
    }

    private boolean genOrderItem(OrderMain order, SubmitOrderVO submitOrderVO, CommonResponse<String> commonResponse) {
        try {
            OrderItem orderItem; /** 生成订单详情 */
            List<SkuIdAndNumEntity> skuIdAndNumEntitys = JSON.parseArray(submitOrderVO.getSku(), SkuIdAndNumEntity.class);
            for (SkuIdAndNumEntity sku : skuIdAndNumEntitys) {
                orderItem = new OrderItem();
                orderItem.setCount(sku.getNum());
                List<Goods> goodses = goodsRepos.findBySku(sku.getId().toString());
                if (Lang.isEmpty(goodses)) {
                    commonResponse.setSuccess(false);
                    commonResponse.setResultMessage("商品" + sku.getId() + "不存在于太平数据库中");
                    return false;
                }
                Goods goods = goodses.get(0);
                orderItem.setGoodsId(goods.getId());
                Product product = goods.getProduct();
                orderItem.setProductId(product.getId());
                ProductFashion productFashion = product.getProductFashions().get(0);
                //都记录成本价
                orderItem.setCostPrice(productFashion.getCostPrice());
                orderItem.setSalePrice(productFashion.getCostPrice());
                orderItem.setProductFashId(productFashion.getId());
                orderItem.setProductName(goods.getName());
                orderItem.setOrder(order);
                order.getOrderItems().add(orderItem);
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            commonResponse.setResultMessage("订单详情生成失败");
            return false;
        }
    }

    private boolean genOrder(OrderMain order, SubmitOrderVO submitOrderVO, CommonResponse<String> commonResponse) {
        try {
            if (submitOrderVO.getTown() == null || submitOrderVO.getTown().equals(0)) {
                submitOrderVO.setTown(null);
            }
            NationalAddress nationalAddress = nationalAddressRepos.findByLeveloneAddressAndLeveltwoAddressAndLevelthreeAddressAndLevelfourAddress(submitOrderVO.getProvince(), submitOrderVO.getCity(), submitOrderVO.getCounty(), submitOrderVO.getTown());
            if (Lang.isEmpty(nationalAddress)) {
                commonResponse.setResultMessage("未找到匹配的地址");
                return false;
            }
            order.setAddressId(nationalAddress.getLinkId());
            order.setMemberId(cyMemberId);
            order.setOrganizationId(cyOrganizationId);
            order.setStoreId("8ce42ec1-8c83-4f22-80c6-e31cdc0dab14");//店鋪id
            order.setOrderItems(new ArrayList<OrderItem>());
            order.setCreateTime(new Date());
            order.setStatus(OrderMain.order_status_neworder);
            order.setOrderNo(orderMainApi.generateOrderNo());
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            commonResponse.setResultMessage("订单生成失败");
            return false;
        }
    }

    @MotanReferer
    OrganizationApi organizationApi;
    @MotanReferer
    OrderMainApi orderMainApi;
    @MotanReferer
    JdProductApi jdProductApi;
    @MotanReferer
    JdOrderApi jdOrderApi;
    @Autowired
    OrderRepos orderRepos;
    @Autowired
    SubOrderRepos subOrderRepos;
    @Autowired
    GoodsRepos goodsRepos;
    @Autowired
    GoodsFashionRepos goodsFashionRepos;
    @Autowired
    NationalAddressRepos nationalAddressRepos;
    @Autowired
    ProductFashionRepos productFashionRepos;
    @Autowired
    JdOrderHelper jdOrderHelper;

}
